<?php
/**
 * $Author: BEESSHOP $
 * ============================================================================
 * ============================================================================
 */
namespace app\module\controllers;

use app\models\AddressRecorder;
use Faker\Provider\Address;

class AddressController extends BaseController{
    public function beforeAction($action)
    {
        if(!$this->check_login()){
            $result = ['result'=>'login_error','data'=>'请先登录'];
            echo json_encode($result);
            return false;
        }
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }


    public function actionAdd(){
        $post = \Yii::$app->request->post();
        $id = intval($post['AddressRecorder']['id']);
        if($id){
            $model = AddressRecorder::find()->where('id=:id',[':id' => $id])->one();
            if(!$model){
                $result = ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
                return json_encode($result);
            }
        }else{
            $model = new AddressRecorder();
            $model->user_id=$this->user->id;
            $model->addtime = time();
        }


        $result = $model->add($post);
        return json_encode($result);
    }


    public function actionList(){
        $list = AddressRecorder::find();
        $list = $list->select(['id','user_name','user_tel','address'])->where('user_id='.$this->user->id)->asArray()->all();
        $result = ['result'=>1,'data'=>$list];
        return json_encode($result);
    }


    public function actionOne(){
        $id = \Yii::$app->request->post('id');
        $model = AddressRecorder::find()->select(['id','user_name','user_tel','address','lat','lng'])->where('id=:id',[':id' => $id])->andWhere('user_id='.$this->user->id)->asArray()->one();
        if(empty($model)){
            $result = ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
            return json_encode($result);
        }
        $result = ['result'=>1,'data'=>$model];
        return json_encode($result);
    }


    public function actionDel(){
        $id = \Yii::$app->request->post('id');
        $model = AddressRecorder::find()->where('id=:id',[':id' => $id])->one();
        if(!$model){
            $result = ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
            return json_encode($result);
        }
        $model->delete();
        $result = ['result'=>1,'data'=>'操作成功'];
        return json_encode($result);
    }


    public function actionGetaddress(){
        $id = \Yii::$app->request->post('id');
        $model = AddressRecorder::find()->select(['id','user_name','user_tel','address'])->where('id=:id',[':id' => $id])->andWhere('user_id='.$this->user->id)->asArray()->one();
        if($model){
            $model['send_time'] = $this->get_send_time($model['id']);
            $result = ['result'=>1,'data'=>$model];
            return json_encode($result);
        }else{
            return;
        }
    }

}
